﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SystemFrameWork
{
    public class StringHelper
    {
        /// <summary>
        /// Compare string ignore case
        /// </summary>
        /// <param name="strA"></param>
        /// <param name="strB"></param>
        /// <returns></returns>
        public static bool EqualIgnoreCase(string strA, string strB)
        {
            if (strA == null || strB == null)
            {
                return false;
            }
            return string.Compare(strA.ToUpper(), strB.ToUpper()) == 0;
        }

        /// <summary>
        /// Format the string with parameters.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string GetStringValue(object source, params object[] parameters)
        {
            if (source == null)
            {
                return string.Empty;
            }
            string msg = source as string;
            if (string.IsNullOrEmpty(msg))
            {
                return string.Empty;
            }
            if (parameters == null || parameters.Length == 0)
            {
                return msg;
            }
            return string.Format(msg, parameters);
        }

        /// <summary>
        /// Get sub string from source if the string length is larger than maxLength
        /// </summary>
        /// <param name="source"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string SubString(string source, int maxLength)
        {
            return source.Length > maxLength ? source.Substring(0, maxLength - 3) + "..." : source;
        }

        public static bool ContainString(string strA, string strB)
        {
            if (strA.IndexOf(strB) >= 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Compare string by number
        /// If A>B then 1
        /// If A=B then 0
        /// else -1
        /// </summary>
        /// <param name="strA"></param>
        /// <param name="strB"></param>
        /// <returns></returns>
        public static int CompareByNumber(string strA, string strB)
        {
            // Validation
            if (string.IsNullOrEmpty(strA) || string.IsNullOrEmpty(strB))
            {
                return 0;
            }

            // Try to parse string to double
            double a;
            double b;
            bool isAParsed = double.TryParse(strA, out a);
            bool isBParsed = double.TryParse(strB, out b);
            if (!isAParsed || !isBParsed)
            {
                return 0;
            }

            if (a > b)
            {
                return 1;
            }
            else if (a == b)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// Get string after last chars
        /// </summary>
        /// <param name="source"></param>
        /// <param name="chars"></param>
        /// <returns></returns>
        public static string GetStringAfterLast(string source, string chars)
        {
            int index = source.LastIndexOf(chars);
            return source.Substring(index + 1);
        }

        public static string GetNotNullString(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            string value = obj as string;
            return value == null ? string.Empty : value;
        }

        /// <summary>
        /// if str is null or empty, not attach it the des,
        /// otherwise. concat the str behind the des.
        /// </summary>
        /// <param name="des"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConcatString(string des, string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return des += str;
            }
            else
            {
                return des;
            }
        }

        /// <summary>
        /// remove ch from target string.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="ch"></param>
        /// <returns></returns>
        public static string RemoveCharacter(string target, string ch)
        {
            return target.Replace(ch, "");
        }

        /// <summary>
        /// Split Str
        /// </summary>
        /// <param name="listStr"></param>
        /// <param name="maxLength"></param>
        /// <param name="delimiter"></param>
        /// <returns></returns>
        public static List<string> SplitStr(List<string> listStr, int maxLength, string delimiter)
        {
            StringBuilder strBuilder = new StringBuilder();

            List<string> listStrResult = new List<string>();
            int count = 0;
            int delimiterCount = delimiter.Length;

            foreach (string str in listStr)
            {
                if ((strBuilder.Length + str.Length) > maxLength)
                {
                    AddListStr(listStrResult, strBuilder, delimiterCount);
                    strBuilder = new StringBuilder();
                    count++;
                    if (count >= 4)
                    {
                        break;
                    }
                    strBuilder.Append(delimiter + str);
                }
                else
                {
                    strBuilder.Append(delimiter + str);
                }
            }

            if (strBuilder.Length != 0)
            {
                AddListStr(listStrResult, strBuilder, delimiterCount);
            }

            if (listStrResult.Count < 4)
            {
                for (int i = listStrResult.Count + 1; i <= 4; i++)
                {
                    listStrResult.Add(string.Empty);
                }
            }

            return listStrResult;
        }

        private static void AddListStr(List<string> listStrResult, StringBuilder strBuilder, int delimiterCount)
        {
            string str1 = strBuilder.ToString();
            str1 = str1.Substring(delimiterCount);
            listStrResult.Add(str1);
        }

        /// <summary> 
        /// Check ID card 
        /// </summary> 
        /// <param name="Id">ID card</param> 
        /// <returns>True or False</returns> 
        public static bool IsIDCard(string Id)
        {
            if (Id.Length == 18)
            {
                bool check = CheckIDCard18(Id);
                return check;
            }
            else if (Id.Length == 15)
            {
                bool check = CheckIDCard15(Id);
                return check;
            }
            else
            {
                return false;
            }
        }


        #region ID card check

        /// <summary> 
        /// Check 15 
        /// </summary> 
        /// <param name="Id">ID card</param> 
        /// <returns> True or False</returns> 
        private static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            //if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            //{
            //    return false;
            //}
            // GB11643-1999  
            return true;
        }

        /// <summary> 
        ///  ID card 18
        /// </summary> 
        /// <param name="Id">ID card</param> 
        /// <returns> True or False</returns> 
        private static bool CheckIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;
            }
            return true;
        }
        #endregion

        /// <summary>
        /// check tel no or mobile no
        /// </summary>
        /// <param name="telNo"></param>
        /// <returns></returns>
        public static bool IsTelNoOrMobileNo(string telNo)
        {
            const string regPattern = @"((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)";
            bool isTel = Regex.IsMatch(telNo, regPattern);
            return isTel;

        }

        /// <summary>
        /// Check mobile no
        /// </summary>
        /// <param name="telNo"></param>
        /// <returns></returns>
        public static bool IsMobileNo(string telNo)
        {
            const string regPattern = @"^13[0-9]{1}[0-9]{8}|^15[9]{1}[0-9]{8}";
            bool isTel = Regex.IsMatch(telNo, regPattern);
            return isTel;

        }

        /// <summary>
        /// extract string from html text
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string ExatractStringFromHtml(string html)
        {
            Regex reg = new Regex(@"()(\\r\\n)|(<.*?>)|(&nbsp;)", RegexOptions.Singleline);
            string ouput = reg.Replace(html, "$1");
            return ouput;
        }

        /// <summary>
        /// Check tel no
        /// </summary>
        /// <param name="telNo"></param>
        /// <returns></returns>
        public static bool IsTelNo(string telNo)
        {
            const string regPattern = "(^[0-9]{3,4}\\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\\([0-9]{3,4}\\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9})";
            bool isTel = Regex.IsMatch(telNo, regPattern);
            return isTel;

        }

        /// <summary>
        /// check the parameter whether follows the Guid type or not
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static bool IsGUID(string expression)
        {
            if (expression != null)
            {
                Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");

                return guidRegEx.IsMatch(expression);
            }
            return false;
        }


        /// <summary>
        /// Check email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsEmail(string email)
        {
            const string regPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            bool isEmail = Regex.IsMatch(email, regPattern);
            return isEmail;
        }

        /// <summary>
        /// check the input string whether it is 
        /// the numeric type[Decimal]
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static bool IsNumeric(string num)
        {
            return Regex.IsMatch(num, @"^[+-]?\d*[.]?\d*$");
        }

        public static string RandomPassword(int length)
        {
            string password = string.Empty;
            Random rd = new Random();

            for (int i = 0; i < length; i++)
            {
                int a = 0;

                a = rd.Next(0, 9);

                password = password + a;
            }

            Encrypt ept = new Encrypt();
            return ept.Encrypto(password);
        }

        /// <summary>
        /// Is person's ID card No.
        /// </summary>
        /// <param name="str_idcard"></param>
        /// <returns></returns>
        public static bool IsIDcard(string str_idcard)
        {
            //15
            if (System.Text.RegularExpressions.Regex.IsMatch(str_idcard, @"/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/"))
            { return true; };
            //18
            if (System.Text.RegularExpressions.Regex.IsMatch(str_idcard, @"[\d]{6}(19|20)*[\d]{2}((0[1-9])|(11|12))([012][\d]|(30|31))[\d]{3}[xX\d]*"))
            { return true; };

            return false;
        }
    }
}
